extends CharacterBody2D


var speed = 100.0
var chase = false
var alive = true

# 配置一个重力
# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")

@onready var player = $"../../Player/Player"
@onready var enemy = $AnimatedSprite2D

func _physics_process(delta):
	# Add the gravity.
	if not is_on_floor():
		velocity.y += gravity * delta
		
	var direction = (player.position - self.position).normalized()
	if alive: 
		if chase == true:
			velocity.x = direction.x * speed
			enemy.play("Run")
		else:
			velocity.x = 0
			enemy.play("Idle")
			
		if direction.x < 0 :
			enemy.flip_h = true
		elif direction.x > 0 :
			enemy.flip_h = false

	move_and_slide()


func _on_area_2d_body_entered(body: Node2D) ->void:
	if body.name == "Player":
		chase = true



func _on_area_2d_body_exited(body: Node2D) ->void:
	if body.name == "Player":
		chase = false



func _on_attacked_body_entered(body: Node2D) ->void:
	if  body.name == "Player":
		if alive == true:
			body.velocity.y -= 300
			death()

func death() ->void:
	alive = false
	enemy.play("Death")
	await enemy.animation_finished
	queue_free()


func _on_attack_body_entered(body):
	if  body.name == "Player":
		if alive == true:
			body.health -= 40
